package com.you.netty.connection;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * 模拟一台机器处理百万并发连接，由于单独一个进程最多可以同时建立60000多个TCP客户端连接,
 * 所以这里启用多个监听端口，每个端口可以接受60000个连接，20个端口则可以接受120万个连接
 */
public class Server {

    public static void main(String[] args) {
        int beginPort = 8000;
        int endPort = 8010;

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup);
        bootstrap.channel(NioServerSocketChannel.class);
        bootstrap.childOption(ChannelOption.SO_REUSEADDR, true);

        bootstrap.childHandler(new ConnectionCountHandler());

        for (int i = 0; i < (endPort - beginPort); i++) {
            final int port = beginPort + i;
            //绑定多个端口
            bootstrap.bind(port).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    System.out.println("bind success in port: " + port);
                }
            });
        }
        System.out.println("server started!");
    }
}
